package com.sport.apis.exception;

import com.sport.model.common.dtos.ResponseResult;
import com.sport.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;

@ControllerAdvice  //控制器增强类
@Slf4j
public class ExceptionCatch {

    /**
     * 处理不可控异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception e){
        e.printStackTrace();
        log.error("catch com.sport.apis.exception:{}",e.getMessage());

        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 处理可控异常  自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult exception(CustomException e){
        log.error("catch com.sport.apis.exception:{}",e.getCause());
        return ResponseResult.errorResult(e.getAppHttpCodeEnum());
    }

    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseResult validException (Exception e) {
        String message = new String();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            message = exception.getBindingResult().getAllErrors().stream().
                    map(returnException->returnException.getDefaultMessage()).
                    collect(Collectors.joining("; "));
        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exception = (ConstraintViolationException) e;
            message = exception.getConstraintViolations().stream().
                    map(returnException->returnException.getMessage()).
                    collect(Collectors.joining("; "));
        } else if (e instanceof BindException) {
            BindException exception = (BindException) e;
            message = exception.getAllErrors().stream().
                    map(returnException->returnException.getDefaultMessage()).
                    collect(Collectors.joining("; "));
        }
        return ResponseResult.errorResult(504,message);
    }
}
